package com.zx.crowdfunding.service.impl;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zx.crowdfunding.entity.Menu;
import com.zx.crowdfunding.entity.MenuExample;
import com.zx.crowdfunding.entity.MenuExample.Criteria;
import com.zx.crowdfunding.mapper.MenuMapper;
import com.zx.crowdfunding.service.api.MenuService;

/**
 * 菜单 - Service接口实现类
 * @author 郑雪
 * @date 2021-12-09
 */
@Service
public class MenuServiceImpl implements MenuService {
	
	/**
	 * 菜单Mapper接口
	 */
	@Autowired
	private MenuMapper menuMapper;

	@Override
	public List<Menu> getAll() {
		return menuMapper.selectByExample(null);
	}

	@Override
	public void saveMenu(Menu menu) {
		menuMapper.insert(menu);
	}

	@Override
	public void removeMenu(List<Integer> idList) {
		MenuExample example = new MenuExample();
		Criteria criteria = example.createCriteria();
		criteria.andIdIn(idList);
		menuMapper.deleteByExample(example);
	}

	@Override
	public Menu getMenuById(Integer id) {
		return menuMapper.selectByPrimaryKey(id);
	}

	@Override
	public void editMenu(Menu menu) {
		menuMapper.updateByPrimaryKeySelective(menu);
	}

	@Override
	public void saveMenuAuthRelationship(Integer menuId,
			List<Integer> authIdList) {
		// 根据menuId删除旧的关联关系数据
		menuMapper.deleteMenuAuthRelationship(menuId);
		
		// 添加菜单与权限的关联关系数据
		if(authIdList != null && authIdList.size()>0){
			menuMapper.insertMenuAuthRelationship(menuId, authIdList);
		}
	}

	@Override
	public LinkedHashSet<Menu> getMenuByAdminId(Integer adminId) {
		
		// 查询全部菜单
		List<Menu> allMenuList = menuMapper.selectByExample(null);
		Map<Integer, Menu> menuMap = new HashMap<Integer, Menu>();
		for (Menu menu : allMenuList) {
			menuMap.put(menu.getId(), menu);
		}
		
		// 根据adminId查询菜单
		List<Menu> adminMenuList = menuMapper.selectMenuByAdminId(adminId);
		
		// 树形结构的菜单集合
		LinkedHashSet<Menu> menuSet = new LinkedHashSet<>();
		
		// 遍历管理员菜单列表，并把所有上级菜单和当前菜单存入menuList中
		for (Menu menu : adminMenuList) {
			if(menu.getPid() != null){
				addAllParentMenu(menuMap.get(menu.getId()), menuMap, menuSet);
			}
		}
		return menuSet;
	}
	
	/**
	 * 把当前菜单的所有上级菜单加到列表中
	 * @param menu 菜单对象
	 * @param allMenuList 全部菜单列表
	 * @param menuList 所有上级菜单列表
	 */
	private void addAllParentMenu(Menu menu, Map<Integer, Menu> menuMap, LinkedHashSet<Menu> menuSet){
		Menu parentMenu = menuMap.get(menu.getPid());
		if(parentMenu.getPid() != null){
			parentMenu.getChildren().add(menu);
			addAllParentMenu(parentMenu, menuMap, menuSet);
		} else {
			menuSet.add(menu);
		}
	}

}
